import Vue from 'vue'
import Vuex from 'vuex'
import { loginApi } from '@/api/index.js'

Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    token: localStorage.getItem('token') || '', // 前面有值用前面的, 前面要是null, 就用后面的
    refresh_token: localStorage.getItem('refresh_token') || '',
    userimg: JSON.parse(localStorage.getItem('user')) || {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    setRefreshToken(state, refresh_token) {
      state.refresh_token = refresh_token
      localStorage.setItem('refresh_token', refresh_token)
    },
    setUserimg(state, userimg) {
      state.userimg = userimg
      localStorage.setItem('user', JSON.stringify(userimg))
    }
  },
  actions: {
    async asyncLoginAction(store, val) {
      try {
        const res = await loginApi(val)
        const { token, refresh_token } = res.data.data
        store.commit('setToken', token)
        store.commit('setRefreshToken', refresh_token)
        return Promise.resolve(res)
      } catch (err) {
        return Promise.reject(err)
      }
    }
  },
  modules: {}
})
